# -*- coding:utf-8 -*-

import configparser
import xlsxwriter
import copy
import os
import time
from datetime import datetime, timedelta


class create_ab_excel(object):
    def __init__(self):
        pass

    def generate_ab_excel(self, title, exceldata):
        try:
            os.remove(r"file/abnormal.xlsx")
        except:
            pass

        try:
            new_date = datetime.now().strftime("%Y%m%d")
            now_date = datetime.now()
            before_data1 = now_date + timedelta(days=-1)
            before_data2 = before_data1.strftime('%Y/%m/%d')
            today_data = datetime.now().strftime("%Y/%m/%d")
            ##创建xlsx状态
            workbook = xlsxwriter.Workbook(r"file/abnormal.xlsx")
            worksheet = workbook.add_worksheet()

            ##格式配置
            worksheet.set_column('A:I', 20)
            # 标题
            format_title = workbook.add_format({'font_size': 20, 'bold': True, 'border': 1})
            format_title.set_align('center')
            format_title.set_align('vcenter')

            # 第一行
            format_h1 = workbook.add_format({'font_size': 12, 'bold': True, 'border': 1})
            format_h1.set_align('center')
            format_h1.set_align('vcenter')

            # 第二行
            format_h2 = workbook.add_format(
                {'font_size': 12, 'bold': True, 'border': 1, 'font_color': '#FF0000', 'bg_color': '#FFFF00'})
            format_h2.set_align('center')
            format_h2.set_align('vcenter')

            # 内容
            format_data = workbook.add_format({'font_size': 10, 'border': 1})
            format_data.set_align('center')
            format_data.set_align('vcenter')

            # 标题二
            format_title_2 = workbook.add_format(
                {'font_size': 12, 'bold': True, 'border': 1, 'font_color': '#FF0000', 'bg_color': '#FFFF00'})
            format_title_2.set_align('center')
            format_title_2.set_align('vcenter')

            # 整合数据
            h2_data1 = ['编号', '系统类型', '模块名称', '异常简述', '异常描述', '解决方式', '服务器', '次数', '最初发生时间']

            # 创建表格
            worksheet.merge_range('A1:I1', title, format_title)
            worksheet.write_row('A2', h2_data1, format_h2)

            # 循环写入数据
            n = 3
            for cae_i in exceldata:
                excel_one = []
                for k, v in cae_i.items():
                    if k != "LAY_TABLE_INDEX":
                        excel_one.append(v)
                worksheet.write_row('A%s' % (n), excel_one, format_data)
                n += 1

            chart1 = workbook.add_chart({'type': 'column'})

            workbook.close()
            print("excel已经生成")
        except BaseException as b:
            _log_err = "generate_ab_excel函数异常 --》" + str(b)

# if __name__ == "__main__":
#     a = create_ab_excel()
#     a.generate_ab_excel('测试')
